﻿(function ($) {
    $.fn.dragable = function (option) {
        option = $.extend({
            handlerSlt: null,
            hideonmove: null
        }, option);
        return this.each(function () {
            var view = $(this);
            var settings = $.extend({}, option);
            var helper = new $.dragableHelper(view, settings);
            view.helper("dragable", helper);
            helper.init();
        });
    };
    $.dragableHelper = function (jo, settings) {
        this.jo = jo;
        this.settings = settings;
        this.enbledrag = true;
        var _this = this;
        this.init = function () {
            var handler = this.jo;
            if (this.settings.handlerSlt) {
                handler = $(this.settings.handlerSlt, this.jo);
            }
            handler.bind('mousedown', this.start);
        };

        this.enable = function () {
            this.enbledrag = true;
        };
        this.disable = function () {
            this.enbledrag = false;
        };
        this.start = function (e) {
            if (!_this.enbledrag) return;
            document.onselectstart = function (e) { return false };
            var o = _this.jo;
            var position = {
                left: o.position().left,
                top: o.position().top,
                x: e.pageX || e.screenX,
                y: e.pageY || e.screenY
            };
            o.data("dragposition", position);
            if (_this.settings.hideonmove) {
                $(_this.settings.hideonmove, o).css({ visibility: "hidden" });
            }
            $(document).bind("mousemove", _this.drag).bind("mouseup", _this.stop);
        };
        this.drag = function (e) {
            if (!_this.enbledrag) return;
            var currposition = {
                x: e.pageX || e.screenX,
                y: e.pageY || e.screenY
            };
            var o = _this.jo;
            var oposition = o.data("dragposition");
            var dertx = currposition.x - oposition.x;
            var derty = currposition.y - oposition.y;
            o.css({ left: (oposition.left + dertx) + "px", top: (oposition.top + derty) + "px" });
        };
        this.stop = function (e) {
            if (!_this.enbledrag) return;
            document.onselectstart = function (e) { return true };
            if (_this.settings.hideonmove) {
                $(_this.settings.hideonmove, _this.jo).css({ visibility: "visible" });
            }
            $(document).unbind('mousemove', _this.drag).unbind('mouseup', _this.stop);
            return _this.preventEvent(e);
        };
        this.preventEvent = function (e) {
            if (e.stopPropagation) e.stopPropagation();
            if (e.preventDefault) e.preventDefault();
            return false;
        }
    }
})(jQuery);